package com.ruge.common.util;

import org.springframework.data.domain.Page;

import java.util.HashMap;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020-03-04  18:15
 * 描述 ：ResponseBody构造器。一般用于ajax、rest等类型的Web服务
 * @author dell
 */
public class RestResponse extends HashMap<String,Object> {

    public static RestResponse success(){
        return success("成功");
    }

    public static RestResponse success(String message){
        RestResponse restResponse = new RestResponse();
        restResponse.setMsg(message);
        restResponse.setCode(0);
        return restResponse;
    }

    public static RestResponse failure(String message){
        RestResponse restResponse = new RestResponse();
        restResponse.setMsg(message);
        restResponse.setCode(-1);
        return restResponse;
    }


    public RestResponse setMsg(String message) {
        if (message != null) {
            put("msg", message);
        }
        return this;
    }

    public RestResponse setData(Object data) {
        if (data != null && data instanceof Page) {
            Page page = (Page) data;
            put("data", page.getContent());
            put("count", page.getTotalElements());
        }else{
            put("data", data);
        }
        return this;
    }

    public RestResponse setCode(Object code) {
        if (code != null) {
            put("code", code);
        }
        return this;
    }


}
